package elitech.vietnam.myfashion;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParserException;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.webkit.URLUtil;
import android.widget.AutoCompleteTextView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.jeremyfeinstein.slidingmenu.lib.SlidingMenu;
import com.koushikdutta.urlimageviewhelper.UrlImageViewHelper;

import elitech.vietnam.myfashion.config.Const;
import elitech.vietnam.myfashion.doinbackground.CallServiceTask;
import elitech.vietnam.myfashion.entites.Category;
import elitech.vietnam.myfashion.entites.City;
import elitech.vietnam.myfashion.entites.District;
import elitech.vietnam.myfashion.entites.Member;
import elitech.vietnam.myfashion.entites.Notify;
import elitech.vietnam.myfashion.entites.Order;
import elitech.vietnam.myfashion.entites.OrderDetail;
import elitech.vietnam.myfashion.entites.Post;
import elitech.vietnam.myfashion.entites.Product;
import elitech.vietnam.myfashion.extend.AsyncTask;
import elitech.vietnam.myfashion.extend.MenuSearchAutoCompleteAdapter;
import elitech.vietnam.myfashion.extend.ViewPagerAdapter;
import elitech.vietnam.myfashion.fragment.DetailFragment;
import elitech.vietnam.myfashion.fragment.EditProfileFragment;
import elitech.vietnam.myfashion.fragment.FollowListFragment;
import elitech.vietnam.myfashion.fragment.MainPageViewFragment;
import elitech.vietnam.myfashion.fragment.MemberStyleFragment;
import elitech.vietnam.myfashion.fragment.NotificationSettingFragment;
import elitech.vietnam.myfashion.fragment.NotificationsFragment;
import elitech.vietnam.myfashion.fragment.ProductFragment;
import elitech.vietnam.myfashion.fragment.SearchFragment;
import elitech.vietnam.myfashion.fragment.StylerFragment;
import elitech.vietnam.myfashion.gcm.GCMIntentService;
import elitech.vietnam.myfashion.utilities.Utilities;
import elitech.vietnam.myfashion.view.EditProfileView;
import elitech.vietnam.myfashion.view.MainPageView;
import elitech.vietnam.myfashion.view.MyShoppingView;
import elitech.vietnam.myfashion.view.MyStyleView;
import elitech.vietnam.myfashion.widgets.CircularImageView;
import elitech.vietnam.myfashion.wsclient.Service;
import eu.janmuller.android.simplecropimage.CropImage;

public class MainActivity extends FragmentActivity implements View.OnClickListener, View.OnFocusChangeListener {

	public static final String IMAGE_TEMP = Environment.getExternalStorageDirectory() + "/ShoppingTemp.jpg";
	public static final int LOGINACTIVITY = 1;
	public static final int CAMERA_MYSTYLE = 2;
	public static final int LIBRAR_MYSTYLE = 3;
	public static final int CAMERA_SETTING = 4;
	public static final int LIBRAR_SETTING = 5;
//	public static final int CROP_FROM_CAMERA = 6;
	public static final int CROP_EDIT_PROFILE = 7;
	
	public static boolean isRunning = false;

	public Category mProductCategory;

	private MainActivity mContext;
	public SlidingMenu mLeftMenu;

	public FragmentManager mFragmentManager;
	public FragmentTransaction mFragmentTransaction;
	public int mScreenWidth, mScreenHeight;
	public Member mUser = null;
	public Order mOrder = null, mBuyNowOrder = null;
	private TextView mBtnBestOfToday, mBtnMenFashion, mBtnWomenFashion, mBtnCategories, mBtnStyler, mBtnMyStyle, mBtnMyShopping, mBtnSetting, mTxtName, mTxtProfile;
	public TextView mBtnNotify, mBtnFriend;
	private AutoCompleteTextView mEdtSearch;
	private ImageButton mBtnSearch;
	public RelativeLayout mLayoutProfile;
	public ImageView mImgHome;
	private CircularImageView mImgAvatar;

	public MainPageView mMainPageView;

	public ArrayList<Product> mListProductBest = new ArrayList<Product>();
	public ArrayList<Product> mListProduct = new ArrayList<Product>();
	public ArrayList<Product> mListFavorite = new ArrayList<Product>();
	public ArrayList<Category> mCategories = new ArrayList<Category>();
	public ArrayList<Category> mFullCategories = new ArrayList<Category>();
	public ArrayList<Post> mListMyStyles = new ArrayList<Post>();
	public ArrayList<Post> mListAllStyle = new ArrayList<Post>();
	public ArrayList<Post> mListFollowStyle = new ArrayList<Post>();
	public ArrayList<City> mListCity = new ArrayList<City>();
	public ArrayList<District> mListDistrict = new ArrayList<District>();
	public ArrayList<Category> mListMaleCategories = new ArrayList<Category>();
	public ArrayList<Category> mListFemaleCategories = new ArrayList<Category>();
	public ArrayList<Notify> mListNotifications = new ArrayList<>();
	public ArrayList<Product> mListSearch = new ArrayList<>();

	public ProgressDialog mLoadingDialog;
	public SharedPreferences mPrefs;
	private Uri mImageCaptureUri;
	public int mLastCartCount;
	public Boolean mEditedInfo = false, isConnectionErrorShow = false;
	public int mFirstStart = 0;
	public int mGenderFashion = 2;

	public MainPageViewFragment mMainPageViewFragment;
	public ProductFragment mProductFragment;
	public FollowListFragment mFollowListFragment;
	public DetailFragment mDetailFragment;
	public StylerFragment mStylerFragment;
	public EditProfileFragment mEditProfileFragment;
	public MemberStyleFragment mMemberStyleFragment;
	public SearchFragment mSearchFragment;
	public NotificationSettingFragment mNotiSettingFragment;
	public NotificationsFragment mNotiFragment;

	public MyShoppingView mMyShoppingView;
	
	public MenuSearchAutoCompleteAdapter mSearchAdapter;
	
	public BroadcastReceiver mNotiReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			Notify noti = new Gson().fromJson(intent.getStringExtra("DATA"), Notify.class);
			if (noti.Type == 4)
				mUser.FollowCount += 1;
			onProfileChanged();
		}
	};
		
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.w("Shopping", "Main onCreate");
		this.mContext = this;
		setContentView(R.layout.mainlayout);

		UrlImageViewHelper.setUseBitmapScaling(true);

		mPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());

		GetListCity();
		GetListDistrict();

		GetLastData();

		DisplayMetrics metrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(metrics);
		mScreenWidth = metrics.widthPixels;
		mScreenHeight = metrics.heightPixels;

		LayoutInit();
		
		IntentFilter filter = new IntentFilter("elitech.vietnam.myfashion.mNotifyReceiver");
		registerReceiver(mNotiReceiver, filter);
		
		onNotificationArrived(getIntent());
	}

	private void LayoutInit() {

		mLoadingDialog = new ProgressDialog(this);
		mLoadingDialog.setCancelable(true);
		mLoadingDialog.setMessage(getString(R.string.loading));

		int menuWidth = mScreenWidth * 75 / 100;
		int numCol = (int) getResources().getDimension(R.dimen.grid_column);
		menuWidth = (numCol == 2 || mContext.mScreenWidth > 2000) ? 528 : menuWidth;
		// menuWidth = (menuWidth > 680) ? 680 : menuWidth;

		mLeftMenu = new SlidingMenu(mContext);
		mLeftMenu.setMode(SlidingMenu.LEFT);
		mLeftMenu.setTouchModeAbove(SlidingMenu.TOUCHMODE_MARGIN);
		mLeftMenu.setShadowWidth(5);
		mLeftMenu.setShadowDrawable(R.drawable.shadow);
		mLeftMenu.setBehindWidth(menuWidth);
		mLeftMenu.setFadeDegree(0.35f);
		mLeftMenu.attachToActivity(mContext, SlidingMenu.SLIDING_CONTENT);
		mLeftMenu.setMenu(R.layout.left_menu);

		mBtnBestOfToday = (TextView) findViewById(R.id.menu_btnBestOfToday);
		mBtnCategories = (TextView) findViewById(R.id.menu_btnCategories);
		mBtnMyShopping = (TextView) findViewById(R.id.menu_btnMyShopping);
		mBtnStyler = (TextView) findViewById(R.id.menu_btnStyler);
		mBtnMyStyle = (TextView) findViewById(R.id.menu_btnMyStyle);
		mBtnSetting = (TextView) findViewById(R.id.menu_btnSetting);
		mBtnMenFashion = (TextView) findViewById(R.id.menu_btnMenFashion);
		mBtnWomenFashion = (TextView) findViewById(R.id.menu_btnWomenFashion);
		mEdtSearch = (AutoCompleteTextView) findViewById(R.id.menu_edtSearch);
		mBtnSearch = (ImageButton) findViewById(R.id.menu_btnSearch);
		mLayoutProfile = (RelativeLayout) findViewById(R.id.menu_layInfo);
		mImgHome = (ImageView) findViewById(R.id.menu_imgLogo);
		mImgAvatar = (CircularImageView) findViewById(R.id.menu_imgAvatar);
		mBtnNotify = (TextView) findViewById(R.id.menu_txtNotifications);
		mBtnFriend = (TextView) findViewById(R.id.menu_txtFriends);
		mTxtName = (TextView) findViewById(R.id.menu_txtName);
		mTxtProfile = (TextView) findViewById(R.id.menu_txtProfile);

		mSearchAdapter = new MenuSearchAutoCompleteAdapter(mContext, android.R.layout.simple_list_item_1, mListSearch);
		mEdtSearch.setAdapter(mSearchAdapter);
		// mBtnMenu.setOnClickListener(this);
		mBtnBestOfToday.setOnClickListener(this);
		mBtnCategories.setOnClickListener(this);
		mBtnStyler.setOnClickListener(this);
		mBtnMyStyle.setOnClickListener(this);
		mBtnMyShopping.setOnClickListener(this);
		mBtnSetting.setOnClickListener(this);
		mBtnMenFashion.setOnClickListener(this);
		mBtnWomenFashion.setOnClickListener(this);
		mBtnSearch.setOnClickListener(this);
		mEdtSearch.setOnFocusChangeListener(this);
		mImgHome.setOnClickListener(this);
		mBtnNotify.setOnClickListener(this);
		mBtnFriend.setOnClickListener(this);

		mMainPageViewFragment = new MainPageViewFragment();
		mFragmentManager = mContext.getSupportFragmentManager();
		mFragmentTransaction = mFragmentManager.beginTransaction();
		mFragmentTransaction.add(R.id.main_layFragment, mMainPageViewFragment);
		mFragmentTransaction.commit();

		onProfileChanged();
	}

	public void replaceFragment(Fragment fragment, boolean isBackStack) {
		if (fragment.isAdded())
			return;
		mFragmentTransaction = mFragmentManager.beginTransaction();
		if (mProductFragment != null && mProductFragment.isAdded()) {
			mFragmentTransaction.hide(mProductFragment);
			mFragmentTransaction.add(mProductFragment.getId(), fragment);
		} else if (mMemberStyleFragment != null && mMemberStyleFragment.isAdded()) {
			mFragmentTransaction.hide(mMemberStyleFragment);
			mFragmentTransaction.add(mMemberStyleFragment.getId(), fragment);
		} else if (mFollowListFragment != null && mFollowListFragment.isAdded()) {
			mFragmentTransaction.hide(mFollowListFragment);
			mFragmentTransaction.add(mFollowListFragment.getId(), fragment);
		} else if (mNotiFragment != null && mNotiFragment.isAdded()) {
			mFragmentTransaction.hide(mNotiFragment);
			mFragmentTransaction.add(mNotiFragment.getId(), fragment);
		} else {
			mFragmentTransaction.hide(mMainPageViewFragment);
			mFragmentTransaction.add(R.id.main_layFragment, fragment);
		}
		if (isBackStack)
			// if(!fragment.isAdded())M
			mFragmentTransaction.addToBackStack(fragment.getTag());
		mFragmentTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
		mFragmentTransaction.commit();
	}

	public Locale getLocale() {
		return getResources().getConfiguration().locale;
	}

	public void AddPreference(String tag, String value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putString(tag, value);
		editor.commit();
	}

	public String GetPreference(String tag) {
		return mPrefs.getString(tag, "");
	}

	public void AddPreferenceInt(String tag, int value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putInt(tag, value);
		editor.commit();
	}

	public int GetPreferenceInt(String tag) {
		return mPrefs.getInt(tag, 0);
	}

	public void AddPreferenceBool(String tag, boolean value) {
		SharedPreferences.Editor editor = mPrefs.edit();
		editor.putBoolean(tag, value);
		editor.commit();
	}

	public boolean GetPreferenceBool(String tag) {
		return mPrefs.getBoolean(tag, true);
	}

	public void onLoginResult(final Intent data) {
		final int result = data.getIntExtra("Id", -1);
		if (result != -1) {
			new CallServiceTask() {
				protected void onPreExecute() {
					mLoadingDialog.show();
				};

				private Member rs = null;

				public void work() {
					try {
						rs = service.getInfoMemberByID(result, -1);
					} catch (IOException e) {} catch (XmlPullParserException e) {}
				};

				protected void onPostExecute(Void result) {
					mLoadingDialog.dismiss();
					mContext.mUser = rs;
					mContext.mOrder = new Order();
					mMainPageView.mPageAdapter = new ViewPagerAdapter(mContext);

					mMainPageView.mViewPager.setAdapter(mMainPageView.mPageAdapter);

					if (mUser != null) {
						AddPreference("User", ConvertToJson(mUser));
						AddPreferenceBool("LoggedIn", true);
//						((MyApplication) getApplicationContext()).startGCMNotification();
					} else {
						AddPreference("User", "");
						AddPreferenceBool("LoggedIn", false);
					}
					int item = -1;
					if ((item = data.getIntExtra("ReturnToTab", -1)) >= 0) {
						Log.w("Shopping", "Get ReturnToTab: " + item);
						mMainPageView.mViewPager.setCurrentItem(item, false);
						data.removeExtra("ReturnToTab");
					}
					onProfileChanged();
				};
			}.execute();
		}
	}
	
	public void onProfileChanged() {
		if (mUser == null) {
			mImgHome.setVisibility(View.VISIBLE);
			mLayoutProfile.setVisibility(View.GONE);
		} else {
			UrlImageViewHelper.setUrlDrawable(mImgAvatar, Const.SERVER_IMAGE_THUMB_URL + mUser.Image, R.drawable.no_avatar1);
			mTxtName.setText((mUser.NickName.length() == 0) ? mUser.Name : mUser.NickName);
			mTxtProfile.setText(mUser.Profile);
			mBtnFriend.setText(mUser.FollowCount + "");
			mImgHome.setVisibility(View.GONE);
			mLayoutProfile.setVisibility(View.VISIBLE);
			mBtnNotify.setText(((MyApplication)getApplicationContext()).mBadge.mBadgeCount + "");
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
		Log.w("MainActivity", "onActivityResult");
		if (requestCode == LOGINACTIVITY) {
			if (resultCode == RESULT_OK) {
				onLoginResult(data);
			}
			if (resultCode == RESULT_CANCELED) {
				// Write your code if there's no result
			}
		}

		if (requestCode == CROP_EDIT_PROFILE) {
			if (resultCode == RESULT_OK) {
				final String path = data.getStringExtra(CropImage.IMAGE_PATH);
				new AsyncTask<Integer, Integer, Boolean>() {
					@Override
					protected Boolean doInBackground(Integer... params) {
						Utilities.createCropImage(path, IMAGE_TEMP);
						return null;
					}

					@Override
					protected void onPostExecute(Boolean result) {
						EditProfileView.mInstance.onActivityResult(IMAGE_TEMP);
					}
				}.execute();
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == CAMERA_MYSTYLE) {
//			if (resultCode == RESULT_OK) {
//				mImageCaptureUri = Uri.fromFile(new File(IMAGE_TEMP));
//				runCropImage();
//			}
//			if (resultCode == RESULT_CANCELED) {
//
//			}
			if (resultCode == RESULT_OK) {
				new AsyncTask<Integer, Integer, Boolean>() {
					private ProgressDialog mProgress;
					@Override
					protected void onPreExecute() {
						mProgress = new ProgressDialog(MainActivity.this);
						mProgress.setMessage(MainActivity.this.getString(R.string.loading));
						mProgress.show();
					}
					@Override
					protected Boolean doInBackground(Integer... params) {
						return Utilities.createCropImage(IMAGE_TEMP, IMAGE_TEMP);
					}
					@Override
					protected void onPostExecute(Boolean result) {
						mProgress.dismiss();
						if (result)
							MyStyleView.mInstance.onActivityResult(IMAGE_TEMP);
						else
							Toast.makeText(mContext, R.string.cannottakephoto, Toast.LENGTH_SHORT).show();
					}
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		}

		if (requestCode == LIBRAR_MYSTYLE) {
			if (resultCode == RESULT_OK) {
				Log.w("Image Path", data.getData().toString());
				new AsyncTask<Integer, Integer, Boolean>() {
					private ProgressDialog mProgress;
					@Override
					protected void onPreExecute() {
						mProgress = new ProgressDialog(MainActivity.this);
						mProgress.setMessage(MainActivity.this.getString(R.string.loading));
						mProgress.show();
					}
					@Override
					protected Boolean doInBackground(Integer... params) {
						String path = getRealPathFromURI(data.getData());
						if (data.getData().toString().startsWith("content://com.google.android.apps.photos.content"))
							path = Utilities.downloadImage(mContext, data.getData().toString(), IMAGE_TEMP);
						return Utilities.createCropImage(path, IMAGE_TEMP);
					}
					@Override
					protected void onPostExecute(Boolean result) {
						mProgress.dismiss();
						if (result)
							MyStyleView.mInstance.onActivityResult(IMAGE_TEMP);
						else
							Toast.makeText(mContext, R.string.cannottakephoto, Toast.LENGTH_SHORT).show();
					}
				}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			}
		}

		if (requestCode == LIBRAR_SETTING) {
			if (resultCode == RESULT_OK) {
//				String path = getRealPathFromURI(data.getData());
//				if (path == null) {
//					Toast.makeText(mContext, mContext.getString(R.string.invalidimage), Toast.LENGTH_SHORT).show();
//					return;
//				}
//				mImageCaptureUri = Uri.fromFile(new File(path));
//				Intent intent = new Intent(this, CropImage.class);
//
//				String filePath = mImageCaptureUri.getPath();
//				Log.w("Shopping", "Path: " + filePath);
				Uri img = data.getData();
				String path = "";
				if (img.toString().startsWith("content://com.android.gallery3d.provider"))
					img = Uri.parse(img.toString().replace("com.android.gallery3d", "com.google.android.gallery3d"));
				path = getRealPathFromURI(img);
				path = (path == null || path.length() == 0) ? img.toString() : path;
				String filePath = "";
				if (URLUtil.isContentUrl(path) || URLUtil.isHttpsUrl(path) || URLUtil.isHttpUrl(path))
					filePath = Utilities.downloadImage(this, path, "");
				else 
					filePath = Utilities.copyFile(getRealPathFromURI(img), "");

				Intent intent = new Intent(this, CropImage.class);
				intent.putExtra(CropImage.IMAGE_PATH, filePath);
				intent.putExtra(CropImage.SCALE, true);
				intent.putExtra(CropImage.ASPECT_X, 1);
				intent.putExtra(CropImage.ASPECT_Y, 1);

				startActivityForResult(intent, CROP_EDIT_PROFILE);
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}

		if (requestCode == CAMERA_SETTING) {
			if (resultCode == RESULT_OK) {
				mImageCaptureUri = Uri.fromFile(new File(IMAGE_TEMP));
				Intent intent = new Intent(this, CropImage.class);

				String filePath = mImageCaptureUri.getPath();
				Log.w("Shopping", "Path: " + filePath);

				intent.putExtra(CropImage.IMAGE_PATH, filePath);
				intent.putExtra(CropImage.SCALE, true);
				intent.putExtra(CropImage.ASPECT_X, 1);
				intent.putExtra(CropImage.ASPECT_Y, 1);

				startActivityForResult(intent, CROP_EDIT_PROFILE);
			}
			if (resultCode == RESULT_CANCELED) {

			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public String getRealPathFromURI(Uri contentUri) {
		String path = null;
		String[] proj = { MediaStore.MediaColumns.DATA };
		Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
		if (cursor.moveToFirst()) {
			int column_index = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATA);
			path = cursor.getString(column_index);
		}
		cursor.close();
		return path;
	}

	public void callMenu() {
		if (!mLeftMenu.isMenuShowing()) {
			mLeftMenu.showMenu();
		} else {
			mLeftMenu.showContent();
		}
	}

	public void callCart() {
		if (mUser == null) {
			Intent intent = new Intent(this, LoginActivity.class);
			intent.putExtra("ReturnToTab", 2);
			startActivityForResult(intent, LOGINACTIVITY);
		} else {
			// mLastTitle = getString(R.string.myshopping);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(2, false);
			mMyShoppingView.showBuying();
		}
		mLeftMenu.showContent();
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.menu_btnBestOfToday:
			// mLastTitle = getString(R.string.bestoftoday);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(0, false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnMenFashion:
			mGenderFashion = 1;
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mMainPageView.mViewPager.getCurrentItem() != 1)
				mMainPageView.mViewPager.setCurrentItem(1, false);
			else
				mMainPageView.mPageAdapter.mCategoriesView.changeGender(mGenderFashion);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnWomenFashion:
			mGenderFashion = 0;
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mMainPageView.mViewPager.getCurrentItem() != 1)
				mMainPageView.mViewPager.setCurrentItem(1, false);
			else
				mMainPageView.mPageAdapter.mCategoriesView.changeGender(mGenderFashion);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnCategories:
			// mLastTitle = getString(R.string.categories);
			mGenderFashion = 2;
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			mMainPageView.mViewPager.setCurrentItem(1, false);
			// changeTitle(getString(R.string.categories), false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnMyShopping:
			if (mUser == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				intent.putExtra("ReturnToTab", 2);
				startActivityForResult(intent, LOGINACTIVITY);
			} else {
				// mLastTitle = getString(R.string.myshopping);
				if (mFragmentManager.getBackStackEntryCount() > 0) {
					for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
						mFragmentManager.popBackStack();
				}
				mMainPageView.mViewPager.setCurrentItem(2, false);
				// changeTitle(getString(R.string.myshopping), false);
			}
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnStyler:
			// mLastTitle = getString(R.string.styler);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mUser == null)
				mMainPageView.mViewPager.setCurrentItem(2, false);
			else
				mMainPageView.mViewPager.setCurrentItem(3, false);
			// changeTitle(getString(R.string.styler), false);
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnMyStyle:
			if (mUser == null) {
				Intent intent = new Intent(this, LoginActivity.class);
				intent.putExtra("ReturnToTab", 4);
				startActivityForResult(intent, LOGINACTIVITY);
			} else {
				// mLastTitle = getString(R.string.mystyle);
				if (mFragmentManager.getBackStackEntryCount() > 0) {
					for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
						mFragmentManager.popBackStack();
				}
				mMainPageView.mViewPager.setCurrentItem(4, false);
			}
			mLeftMenu.showContent();
			break;
		case R.id.menu_btnSetting:
			// mLastTitle = getString(R.string.setting);
			if (mFragmentManager.getBackStackEntryCount() > 0) {
				for (int i = 0; i < mFragmentManager.getBackStackEntryCount(); i++)
					mFragmentManager.popBackStack();
			}
			if (mUser == null)
				mMainPageView.mViewPager.setCurrentItem(3, false);
			else
				mMainPageView.mViewPager.setCurrentItem(5, false);
			mLeftMenu.showContent();
			break;
//		case R.id.menu_edtSearch:
//			CallSearch();
//			break;
		case R.id.menu_imgLogo:
			Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(getString(R.string.homepageurl)));
			startActivity(browserIntent);
			break;
		case R.id.menu_txtNotifications:
			if (mContext.mNotiFragment == null)
				mContext.mNotiFragment = new NotificationsFragment();
			if (!mContext.mNotiFragment.isAdded()) {
				mContext.replaceFragment(mContext.mNotiFragment, true);
			}
			mLeftMenu.showContent();
			break;
		case R.id.menu_txtFriends:
			if (mFollowListFragment == null)
				mFollowListFragment = new FollowListFragment();
			if (!mFollowListFragment.isAdded()) {
				replaceFragment(mFollowListFragment, true);
			}
			mLeftMenu.showContent();
			break;
		}
	}

	public void GetListCity() {
		new CallServiceTask() {
			private ArrayList<City> rs = new ArrayList<City>();

			public void work() {
				try {
					rs = service.getListCity();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mListCity.addAll(rs);
			};
		}.execute();
	}

	public void GetListDistrict() {
		new CallServiceTask() {
			private ArrayList<District> rs = new ArrayList<District>();

			public void work() {
				try {
					rs = service.getListDistrict();
				} catch (IOException e) {} catch (XmlPullParserException e) {}
			};

			protected void onPostExecute(Void result) {
				mListDistrict.addAll(rs);
			};
		}.execute();
	}

	private boolean isBack = false;

	@Override
	public void onLowMemory() {
		super.onLowMemory();
	}
	
	@Override
	protected void onStart() {
		super.onStart();
//		((MyApplication) getApplicationContext()).mBadge.hideBadge();
		isRunning = true;
	}

	@Override
	public void onBackPressed() {
		if (mLeftMenu.isMenuShowing()) {
			mLeftMenu.showContent();
		} else if (mFragmentManager.getBackStackEntryCount() > 0)
			if (mDetailFragment != null && mDetailFragment.isAdded()) {
				if (mDetailFragment.view != null && mDetailFragment.view.PopBack()) {
					Back();
				}
			} else
				Back();
		else {
			if (isBack) {
				Back();
			} else {
				if (mMainPageView.mViewPager.getCurrentItem() != 0)
					mMainPageView.mViewPager.setCurrentItem(0, false);
				else {
					isBack = true;
					Timer timer = new Timer();
					timer.schedule(new TimerTask() {
						@Override
						public void run() {
							isBack = false;
						}
					}, 2000);
					Toast.makeText(mContext, getString(R.string.backexit), Toast.LENGTH_SHORT).show();
				}
			}
		}
	}

	public void Back() {
		super.onBackPressed();
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_MENU) {
			if (!mLeftMenu.isMenuShowing()) {
				mLeftMenu.showMenu();
			} else {
				mLeftMenu.showContent();
			}
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	void GetLastData() {
		Gson gson = new Gson();
		mOrder = new Order();
		// mStartedPos = GetPreferenceInt("ViewState");
		String order = GetPreference("Order");
		if (!order.equals("")) {
			mOrder.ListDetail = gson.fromJson(order, new TypeToken<ArrayList<OrderDetail>>() {}.getType());
		}

		String user = GetPreference("User");
		if (!user.equals("")) {
			mUser = gson.fromJson(user, Member.class);
			AddPreferenceBool("LoggedIn", true);
//			if (GetPreferenceBool("GetNotification"))
//				((MyApplication) getApplicationContext()).startGCMNotification();
		}

		String best = GetPreference("ListProductBest");
		if (!best.equals("")) {
			mListProductBest = gson.fromJson(best, new TypeToken<ArrayList<Product>>() {}.getType());
		}
	}

	public String ConvertToJson(Object O) {
		Gson gson = new Gson();
		return gson.toJson(O);
	}

	@Override
	protected void onStop() {
		Log.w("Shopping", "onStop");
		super.onStop();
		isRunning = false;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		Log.w("MainActivity", "onPause");
	}

	@Override
	protected void onResume() {
		super.onResume();
		Log.w("MainActivity", "onResume");
		getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
		// onNotificationArrived(getIntent());
	}

	@Override
	public void onAttachedToWindow() {
		super.onAttachedToWindow();
		Log.w("Shopping", "onAttachedToWindow");
		mFirstStart = GetPreferenceInt("FirstStart");
		Log.w("Shopping", "mFirstStart = " + mFirstStart);
		if (mFirstStart != 0) {
			AddPreferenceInt("FirstStart", 0);
			Intent intent = new Intent(mContext, MainActivity.class);
			if (getIntent().getExtras() != null) {
				String notiExtras = getIntent().getExtras().getString(GCMIntentService.DATA_TAG);
				if (notiExtras != null && !notiExtras.equals(""))
					intent.putExtra(GCMIntentService.DATA_TAG, notiExtras);
				int i = getIntent().getIntExtra("ReusumeReturnToTab", -1);
				if (i > 0)
					intent.putExtra("ReusumeReturnToTab", i);
			}
			mContext.startActivity(intent);
			mContext.finish();
			return;
		} else {
			mFirstStart = 1;
			AddPreferenceInt("FirstStart", mFirstStart);
			Log.w("Shopping", "mFirstStart = " + mFirstStart);
		}
		int returnTo = getIntent().getIntExtra("ReusumeReturnToTab", -1);
		if (returnTo > 0) {
			Log.w("ReusumeReturnToTab", "onResume " + returnTo);
			mMainPageView.mViewPager.setCurrentItem(returnTo, false);
			getIntent().removeExtra("ReusumeReturnToTab");
		}
	}

	public void SaveListBestToCache() {
		if (mListProductBest.size() != 0) {
			AddPreference("ListProductBest", ConvertToJson(mListProductBest));
		} else {
			AddPreference("ListProductBest", "");
		}
	}

	@Override
	protected void onDestroy() {
		Log.w("Shopping", "onDestroy");
		AddPreferenceInt("FirstStart", 0);
		AddPreferenceInt("ViewState", 0);
		if (mOrder != null) {
			AddPreference("Order", ConvertToJson(mOrder.ListDetail));
		} else {
			AddPreference("Order", "");
		}
		if (mUser != null) {
			AddPreference("User", ConvertToJson(mUser));
		} else {
			AddPreference("User", "");
		}
		if (mListProductBest.size() != 0) {
			AddPreference("ListProductBest", ConvertToJson(mListProductBest));
		} else {
			AddPreference("ListProductBest", "");
		}
		unregisterReceiver(mNotiReceiver);
		super.onDestroy();
	}
	
	@Override
	protected void onPostResume() {
		Log.w("Shopping", "onPostResume");
		super.onPostResume();
	}

	@Override
	protected void onNewIntent(Intent intent) {
		Log.w("Push Notification", "onNewIntent");
		super.onNewIntent(intent);
		onNotificationArrived(intent);
	}

	private void onNotificationArrived(final Intent intent) {
		final Bundle extras = intent.getExtras();
		if (extras != null && extras.containsKey(GCMIntentService.DATA_TAG) && !extras.getString(GCMIntentService.DATA_TAG).equals("")) {
			Log.w("Push Notification", "has " + GCMIntentService.DATA_TAG + " extra");
			((MyApplication) getApplicationContext()).mBadge.hideBadge();
			mPrefs.edit().putInt("mBadgeCount", ((MyApplication)getApplicationContext()).mBadge.mBadgeCount).commit();
			final Notify noti = new Gson().fromJson(extras.getString(GCMIntentService.DATA_TAG), Notify.class);
			new AsyncTask<Integer, Integer, Boolean>() {
				@Override
				protected Boolean doInBackground(Integer... params) {
					try {
						new Service().readNotification(noti.Id);
					} catch (IOException | XmlPullParserException e) {
						e.printStackTrace();
					}
					return null;
				}
			}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
			Runnable runnable = null;
			if (noti.Type == 1 || noti.Type == 2 || noti.Type == 3) {
				runnable = new Runnable() {
					@Override
					public void run() {
						final boolean myStyle = (mUser != null && mUser.Id == noti.OwnerID);
						if (mMainPageView == null) {
							if (mContext.mStylerFragment == null)
								mContext.mStylerFragment = new StylerFragment() {
									@Override
									public void onCreate(Bundle savedInstanceState) {
										super.onCreate(savedInstanceState);
										extras.remove(GCMIntentService.DATA_TAG);
									}
								};
							if (!mContext.mStylerFragment.isAdded()) {
								mStylerFragment.setPostID(noti.PostID, myStyle);
								replaceFragment(mContext.mStylerFragment, true);
							}
						} else {
							int mTab = mMainPageView.mViewPager.getCurrentItem();
							if (mTab != 3 || mTab != 4)
								mMainPageView.mViewPager.setCurrentItem(4);
							mFragmentManager.popBackStackImmediate();
							mContext.mStylerFragment = new StylerFragment() {
								@Override
								public void onCreate(Bundle savedInstanceState) {
									super.onCreate(savedInstanceState);
									intent.removeExtra(GCMIntentService.DATA_TAG);
								}
							};
							mStylerFragment.setPostID(noti.PostID, myStyle);
							replaceFragment(mContext.mStylerFragment, true);
						}
					}
				};
			}
			if (noti.Type == 4) {
				runnable = new Runnable() {
					@Override
					public void run() {
						if (mFollowListFragment == null)
							mFollowListFragment = new FollowListFragment() {
							@Override
							public void onCreate(Bundle savedInstanceState) {
								super.onCreate(savedInstanceState);
								intent.removeExtra(GCMIntentService.DATA_TAG);
							}
						};
						Bundle bundle = new Bundle();
						bundle.putInt("TAB", 1);
						mFollowListFragment.setArguments(bundle);
						if (!mFollowListFragment.isAdded()) {
							replaceFragment(mFollowListFragment, true);
						}
					}
				};
			}
			if (noti.Type == 5) {
				runnable = new Runnable() {
					@Override
					public void run() {
						if (mDetailFragment == null)
							mDetailFragment = new DetailFragment() {
								@Override
								public void onCreate(Bundle savedInstanceState) {
									super.onCreate(savedInstanceState);
									extras.remove(GCMIntentService.DATA_TAG);
								}
							};
						if (!mDetailFragment.isAdded()) {
							mDetailFragment.setProductID(noti.PostID);
							replaceFragment(mDetailFragment, true);
						}
					}
				};
			}
			if (runnable != null)
				new Handler().postDelayed(runnable, 400);
//			if (noti.CommentType == 1) {
//				if (mDetailFragment == null)
//					mDetailFragment = new DetailFragment() {
//						@Override
//						public void onCreate(Bundle savedInstanceState) {
//							super.onCreate(savedInstanceState);
//							extras.remove(GCMIntentService.DATA_TAG);
//						}
//					};
//				if (!mDetailFragment.isAdded()) {
//					mDetailFragment.setProductID(noti.PostID);
//					replaceFragment(mDetailFragment, true);
//				}
//			}
//			if (noti.CommentType == 2) {
//				final boolean myStyle = (mUser != null && mUser.Id == noti.MemID);
//				if (mMainPageView == null) {
//					if (mContext.mStylerFragment == null)
//						mContext.mStylerFragment = new StylerFragment() {
//							@Override
//							public void onCreate(Bundle savedInstanceState) {
//								super.onCreate(savedInstanceState);
//								extras.remove(GCMIntentService.DATA_TAG);
//							}
//						};
//					if (!mContext.mStylerFragment.isAdded()) {
//						mStylerFragment.setPostID(noti.PostID, myStyle);
//						replaceFragment(mContext.mStylerFragment, true);
//					}
//				} else {
//					int mTab = mMainPageView.mViewPager.getCurrentItem();
//					if (mTab != 3 || mTab != 4)
//						mMainPageView.mViewPager.setCurrentItem(4);
//					mFragmentManager.popBackStackImmediate();
//					mContext.mStylerFragment = new StylerFragment() {
//						@Override
//						public void onCreate(Bundle savedInstanceState) {
//							super.onCreate(savedInstanceState);
//							intent.removeExtra(GCMIntentService.DATA_TAG);
//						}
//					};
//					mStylerFragment.setPostID(noti.PostID, myStyle);
//					replaceFragment(mContext.mStylerFragment, true);
//				}
//			}
			GCMIntentService.NUMBER = 0;
		}
	}
	
	public void CallSearch() {
		
	}

	@Override
	public void onFocusChange(View v, boolean hasFocus) {
		if (v.getId() == R.id.menu_edtSearch && !hasFocus) {
			InputMethodManager inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
	    	inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
	    	((AutoCompleteTextView) v).setText("");
		}
	}
	
}
